<?php
/*
	Copyright © Eleanor CMS
	URL: http://eleanor-cms.ru, http://eleanor-cms.com
	E-mail: support@eleanor-cms.ru
	Developing: Alexander Sunvas*
	Interface: Rumin Sergey
	=====
	*Pseudonym
*/
if(!defined('CMS'))die;
global$Eleanor,$head,$title;
$Eleanor->module['config']=include($Eleanor->module['path'].'config.php');
$l=Eleanor::$Language->Load($Eleanor->module['path'].'lang_user-*.php',$Eleanor->module['config']['n']);
$Eleanor->module['config']['etag']='';#Дополнение к ETAG

$Lst=Eleanor::LoadListTemplate('headfoot');
$u='?'.Url::Query(Eleanor::$vars['multilang'] && Language::$main!=LANGUAGE ? array('lang'=>Eleanor::$langs[Language::$main]['uri'],'module'=>$Eleanor->module['name']) : array('module'=>$Eleanor->module['name']));
$Eleanor->module['config']['rss']=Eleanor::$services['rss']['file'].$u;
$head['rss']=$Lst->link(array(
	'rel'=>'alternate',
	'type'=>'application/rss+xml',
	'href'=>$Eleanor->module['config']['rss'],
	'title'=>$l['catalog'],
));
$head['search']=$Lst->link(array(
	'rel'=>'search',
	'type'=>'application/opensearchdescription+xml',
	'title'=>$l['catalog'],
	'href'=>Eleanor::$services['xml']['file'].$u,
));

Eleanor::LoadOptions($Eleanor->module['config']['opts']);
Eleanor::$Template->queue[]=$Eleanor->module['config']['usertpl'];

$curls=array();
$catalog=false;
if($Eleanor->Url->is_static) {
	$str=$Eleanor->Url->GetEnding(array($Eleanor->Url->ending,$Eleanor->Url->delimiter),true);
	$_GET+=$Eleanor->Url->Parse($str ? array() : array('do'));
	if($str)
	{
		$curls=isset($_GET['']) ? (array)$_GET[''] : array();
		if($str==$Eleanor->Url->ending and !isset($_GET['page']))
			$catalog=array_pop($curls);
	}
}
$cid=isset($_GET['cid']) ? (int)$_GET['cid'] : 0;
$nid=isset($_GET['nid']) ? (int)$_GET['nid'] : 0;

$Eleanor->Categories->Init($Eleanor->module['config']['c']);

if(isset($_GET['do'])) {
	$d=(string)$_GET['do'];
	switch($d) {
		case'categories':
			if(!$Eleanor->Categories->dump)
				return GoAway();
			global$title;
			$title[]=Eleanor::$Language[$Eleanor->module['config']['n']]['categs'];
			$c=Eleanor::$Template->ShowCategories();
			Start();
			echo$c;
		break;
		default:
			if(preg_match('#^(\d{4})\D(\d{1,2})(?:\D(\d{1,2}))?$#',$d,$ma)>0) {
				if(strtotime($d) > time())
					return GoAway(true);
				$title[]=sprintf(Eleanor::$Language[$Eleanor->module['config']['n']]['catalog_for'],Eleanor::$Language->Date($d,strlen($d)>7 ? 'fd' : 'my',array('lowercase'=>true)));
				$R = Eleanor::$Db->Query('SELECT COUNT(`lstatus`) FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language`IN(\'\',\''.Language::$main.'\') AND `lstatus`=1 AND IF(`pinned`=\'0000-00-00 00:00:00\',`date`,`pinned`) LIKE \''.$d.'%\'');
				list($cnt)=$R->fetch_row();

				$np=$cnt % Eleanor::$vars['publ_per_page'];
				$pages=max(ceil($cnt/Eleanor::$vars['publ_per_page'])-($np>0 ? 1 : 0),1);
				$page=isset($_GET['page']) ? (int)$_GET['page'] : $pages;
				$intpage=$pages - $page + 1;
				$offset=max(0,$intpage-1)*Eleanor::$vars['publ_per_page'];

				$limit=Eleanor::$vars['publ_per_page'];
				if($offset==0)
					$limit+=$np;
				else
					$offset+=$np;

				if($cnt and $offset>=$cnt)
					$offset=max(0,$cnt-$limit);
				$r=$R = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned`=\'0000-00-00 00:00:00\',`date`,`pinned`) `date`,`author`,`author_id`,`show_detail`,`status`,`reads`,`comments`,`uri`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod` FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language`IN(\'\',\''.Language::$main.'\') AND `lstatus`=1 AND IF(`pinned`=\'0000-00-00 00:00:00\',`date`,`pinned`) LIKE \''.$d.'%\' ORDER BY `ldate` DESC LIMIT '.$offset.', '.$limit);
				$data=CatalogList($r);
				if(!$data)
					return;
				$c=Eleanor::$Template->CatalogDateList($d,$data,$cnt-$np,$page,Eleanor::$vars['publ_per_page']);
				$Eleanor->origurl=PROTOCOL.Eleanor::$punycode.Eleanor::$site_path.$Eleanor->Url->Construct(array('do'=>$d),true,'');
				Start();
				echo$c;
			}
			else
				ExitPage();
	}
} elseif($nid or $catalog) {
	$where = $nid ? '`id`='. (int)$nid : '`uri`=\''.Eleanor::$Db->Escape($catalog,false).'\'';
	$uid = (int)Eleanor::$Login->GetUserValue('id');
	$gn = $uid==0 ? GetGN() : array();

	$R = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned`=\'0000-00-00 00:00:00\',`date`,`pinned`) `date`,`author`,`author_id`,`show_sokr`,`status`,`reads`,`comments`,`status`,`uri`,`title`,`text`, `info`,`meta_title`,`meta_descr`,UNIX_TIMESTAMP(`last_mod`) `last_mod`, `price`, `advertisement` FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language`IN(\'\',\''.Language::$main.'\') AND '.$where.' LIMIT 1');
	if(!$a=$R->fetch_assoc())
		return ExitPage();
	$a['_canedit']=Eleanor::$Permissions->IsAdmin() || ($uid>0 and $a['author_id']==$uid or $uid==0 and in_array($a['id'],$gn));
	if($a['status']!=1 and !$a['_canedit'])
		return ExitPage();
	$Eleanor->module['config']['catalogid']=$a['id'];
	$a['_cat']=$a['cats'] ? (int)ltrim($a['cats'],',') : false;
	$u=array('u'=>array($a['uri'],'nid'=>$a['id']));
	if($a['_cat'] and $Eleanor->Url->furl) {
		$cu=$Eleanor->Categories->GetUri($a['_cat']);
		if($cu)
			$u=$cu+$u;
	}
	if($cid or $curls or $nid and $a['uri']) {
		$category=$Eleanor->Categories->GetCategory($cid,$curls);
		if($category and $category['id']!=$a['_cat']) {
			$commu=$Eleanor->Comments->GET();
			foreach($commu as $k=>$v)
				$u[]=array($k=>$v);
			return GoAway($u);
		}
	}

	$images = array();
	$R = Eleanor::$Db->Query('SELECT `image` FROM `'. $Eleanor->module['config']['i'] .'` WHERE `catalog_id` = "'. $a['id'] .'"');
	while($ia = $R->fetch_row()) {
		if ($ia)
			$images[] = $ia;
	}
	if(!Eleanor::$is_bot and $a['status']==1) {
		#Не будем увеличивать счетчик просмотров от переходов по страницам новости
		$ref=getenv('HTTP_REFERER');
		$uu=PROTOCOL.Eleanor::$punycode.Eleanor::$site_path.$Eleanor->Url->Construct($u,true,'');
		$uu=htmlspecialchars_decode($uu,ELENT);
		if(strpos($ref,$uu)===false)
			Eleanor::$Db->Update($Eleanor->module['config']['t'],array('!reads'=>'`reads`+1'),'`id`='.$a['id'].' LIMIT 1');
	}

	if(Eleanor::$caching) {
		Eleanor::$last_mod=$a['last_mod'];
		$etag=Eleanor::$etag;
		$uid=Eleanor::$Login->GetUserValue('id');
		Eleanor::$etag=md5($uid.'-'.$a['id'].'-'.$Eleanor->module['config']['n'].$Eleanor->module['config']['etag']);
		if(Eleanor::$modified and Eleanor::$last_mod and Eleanor::$last_mod<=Eleanor::$modified and $etag and $etag==Eleanor::$etag)
			return Start();
		else
			Eleanor::$modified=false;
	}

	if($a['meta_title'])
		$title=$a['meta_title'];
	else
		$title[]=$a['title'];

	if($a['meta_descr'])
		$Eleanor->module['config']['description'] = $a['meta_descr'];

	OwnBB::$opts['alt'] = $a['title'];

	$Eleanor->origurl = PROTOCOL . Eleanor::$punycode.Eleanor::$site_path.$Eleanor->Url->Construct($u);
	$a['text'] = OwnBB::Parse($a['text']);

	#Поддержка соцсетей:
	$Lst=Eleanor::LoadListTemplate('headfoot')
		->og('title', $a['title'])
		->og('uri', $Eleanor->origurl)
		->og('locale', Eleanor::$langs[Language::$main]['d'])
		->og('site_name', Eleanor::$vars['site_name']);
	if($a['meta_descr'])
		$Lst->og('description', $a['meta_descr']);
	if(preg_match('#<img.+?src="([^"]+)"[^>]*>#', $a['text'], $m) > 0)
		$Lst->og('image', strpos($m[1],'://') === false ? PROTOCOL . Eleanor::$punycode . Eleanor::$site_path . $m[1] : $m[1]);
	$GLOBALS['head']['og'] = (string)$Lst;

	if(!$Eleanor->Comments->off)
		$Eleanor->Comments->baseurl = array('module' => $Eleanor->module['name']) + $u;
	$c = Eleanor::$Template->ShowCatalog($a, ($Eleanor->Comments->off ? '' : $Eleanor->Comments->Show($a['id'])), $images);
	Start();
	echo$c;
} elseif($cid or $curls) {
	$category = $Eleanor->Categories->GetCategory($cid, $curls);
	if(!$category)
		return ExitPage();
	$Lst=Eleanor::LoadListTemplate('headfoot');
	$head['rss'] = $Lst->link(array(
		'rel'=>'alternate',
		'type'=>'application/rss+xml',
		'href'=>Eleanor::$services['rss']['file'].'?'.Url::Query(Eleanor::$vars['multilang'] && Language::$main!=LANGUAGE ? array('lang'=>Eleanor::$langs[Language::$main]['uri'],'module'=>$Eleanor->module['config']['name'],'c'=>$category['id']) : array('module'=>$Eleanor->module['config']['name'],'c'=>$category['id'])),
		'title'=>sprintf(Eleanor::$Language[$Eleanor->module['config']['n']]['catalogfrom'],$category['title']),
	));
	if($category['meta_title'])
		$title = $category['meta_title'];
	else
		$title[] = $category['title'];

	if($category['meta_descr'])
		$Eleanor->module['config']['description'] = $category['meta_descr'];

	if(Eleanor::$vars['publ_catsubcat']) {
		$carr = array($category['id']);
		$p=$category['parents'].$category['id'].',';
		foreach($Eleanor->Categories->dump as $k => &$v)
			if(strpos($v['parents'],$p) === 0)
				$carr[] = $k;
		$cwhere = count($carr) > 1 ? 'REGEXP (\',('.join('|',$carr).'),\')' : 'LIKE \'%,'.$category['id'].',%\'';
	}
	else
		$cwhere = 'LIKE \'%,'.$category['id'].',%\'';
	$R = Eleanor::$Db->Query('SELECT COUNT(`lstatus`) FROM `'.$Eleanor->module['config']['tl'].'` WHERE `language`IN(\'\',\''.Language::$main.'\') AND `lstatus`=1 AND `lcats` '.$cwhere.'');
	list($cnt)=Eleanor::$Db->FetchRow();

	$np = $cnt % Eleanor::$vars['publ_per_page'];
	$pages = max(ceil($cnt/Eleanor::$vars['publ_per_page'])-($np>0 ? 1 : 0),1);
	$page = isset($_GET['page']) ? (int)$_GET['page'] : $pages;
	$intpage = $pages - $page + 1;
	$offset = max(0,$intpage-1)*Eleanor::$vars['publ_per_page'];

	$limit = Eleanor::$vars['publ_per_page'];
	if($offset == 0)
		$limit+=$np;
	else
		$offset+=$np;

	if($cnt && $offset>=$cnt)
		$offset = max(0,$cnt-$limit);
	$r = Eleanor::$Db->Query('SELECT `id`,`cats`,IF(`pinned`=\'0000-00-00 00:00:00\',`date`,`pinned`) `date`,`author`,`author_id`,`show_detail`,`status`,`reads`,`comments`,`uri`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod` FROM `'.$Eleanor->module['config']['t'].'` INNER JOIN `'.$Eleanor->module['config']['tl'].'` USING(`id`) WHERE `language`IN(\'\',\''.Language::$main.'\') AND `lstatus`=1 AND `lcats` '.$cwhere.' ORDER BY `ldate` DESC LIMIT '.$offset.', '.$limit);
	$d = CatalogList($r);
	if(!$d)
		return;
	$c = Eleanor::$Template->CatalogCategoryList($category,$d,$cnt-$np,$page,Eleanor::$vars['publ_per_page']);
	$Eleanor->origurl=PROTOCOL.Eleanor::$punycode.Eleanor::$site_path.$Eleanor->Url->Construct($Eleanor->Categories->GetUri($category['id'])+array('page'=>array('page'=>$page==$pages ? false : $page)),true,$Eleanor->Url->delimiter);

	#Поддержка соцсетей:
	$Lst=Eleanor::LoadListTemplate('headfoot');
	$GLOBALS['head']['og']=$Lst->og('title',$category['title'])
		.$Lst->og('uri',$Eleanor->origurl)
		.$Lst->og('locale',Eleanor::$langs[Language::$main]['d'])
		.$Lst->og('site_name',Eleanor::$vars['site_name']);
	if($category['meta_descr'])
		$GLOBALS['head']['og'].=$Lst->og('description',$category['meta_descr']);
	if($category['image'])
		$GLOBALS['head']['og'].=$Lst->og('image',PROTOCOL.Eleanor::$punycode.Eleanor::$site_path.$Eleanor->Categories->imgfolder.$category['image']);

	Start();
	echo$c;
} else
	CatalogBeginPage();

function CatalogBeginPage()
{global$Eleanor,$title;
	$title[]=Eleanor::$Language[$Eleanor->module['config']['n']]['catalog'];

	$R = Eleanor::$Db->Query('SELECT COUNT(`status`) FROM `'.$Eleanor->module['config']['t'].'` WHERE `status`=1');
	list($cnt)=$R->fetch_row();

	$np=$cnt % Eleanor::$vars['publ_per_page'];
	$pages=max(ceil($cnt/Eleanor::$vars['publ_per_page'])-($np>0 ? 1 : 0),1);
	$page=isset($_GET['page']) ? (int)$_GET['page'] : $pages;
	$intpage=$pages - $page + 1;
	$offset=max(0,$intpage-1)*Eleanor::$vars['publ_per_page'];

	$limit=Eleanor::$vars['publ_per_page'];
	if($offset==0)
		$limit+=$np;
	else
		$offset+=$np;

	if($cnt and $offset>=$cnt) {
		$offset=max(0,$cnt-$limit);
	}

	if (isset($_GET['sort'])) {
		switch($_GET['sort']) {
			case'view':
				$order = '`reads` DESC';
			break;
			case'alpha':
				$order = '`title`';
			break;
			case'price':
				$order = '`price`';
			break;
		}
	} else {
		$order = '`ldate` DESC';
	}

	$r = Eleanor::$Db->Query('SELECT `c`.`id`,`cats`,IF(`pinned`=\'0000-00-00 00:00:00\',`date`,`pinned`) `date`,`author`,`author_id`,`show_detail`,`status`,`reads`,`comments`,`uri`,`title`,`text`,UNIX_TIMESTAMP(`last_mod`) `last_mod`,`price`, (SELECT `image` FROM `'. $Eleanor->module['config']['i'] .'` WHERE `catalog_id` = `c`.`id` LIMIT 1) `image`
	FROM `'.$Eleanor->module['config']['t'].'` AS `c`
	INNER JOIN `'.$Eleanor->module['config']['tl'].'` AS `cl` USING(`id`)
	WHERE `language`IN(\'\',\''.Language::$main.'\') AND `lstatus`=1 ORDER BY '. $order .' LIMIT '.$offset.', '.$limit);
	$d=CatalogList($r,empty($Eleanor->module['config']['general']));
	if(!$d)
		return;
	$links=array(
		'first_page'=>$Eleanor->Url->Prefix(false),
		'pages'=>function($n){ return$GLOBALS['Eleanor']->Url->Construct(array(array('page'=>$n))); },
	);
	$c=Eleanor::$Template->CatalogList($d,$cnt-$np, -$page, $pages, Eleanor::$vars['publ_per_page'], $links);
	$Eleanor->origurl=PROTOCOL.Eleanor::$punycode.Eleanor::$site_path.$Eleanor->Url->Construct(array('page'=>array('page'=>$page==$pages ? false : $page)));
	Start();
	echo$c;
}

function CatalogList($r,$caching=true,$anurl=array())
{global$Eleanor;
	$items = $ucats = array();
	$lmod = 0;
	$ids = ',';
	$uid = (int)Eleanor::$Login->GetUserValue('id');
	if($r && $r->num_rows > 0) {
		$isa = Eleanor::$Permissions->IsAdmin();
		$gn = $uid == 0 ? GetGN() : array();

		while($a = $r->fetch_assoc()) {
			$a['_canedit'] = $isa || ($uid > 0 and $a['author_id'] == $uid || $uid == 0 and in_array($a['id'], $gn));

			$ids .= $a['id'] .',';
			if($a['last_mod'] > $lmod)
				$lmod=$a['last_mod'];

			$a['_cat']=$a['cats'] ? (int)ltrim($a['cats'],',') : false;
			if($a['_cat'] && !isset($ucats[$a['_cat']]))
				$ucats[$a['_cat']]=$Eleanor->Categories->GetUri($a['_cat']);

			OwnBB::$opts['alt']=$a['title'];
			$a['text']=OwnBB::Parse($a['text']);

			$u=array('u'=>array($a['uri'],'nid'=>$a['id']))+$anurl;
			$a['_url'] = $Eleanor->Url->Construct($a['_cat'] && $Eleanor->Url->furl && isset($ucats[$a['_cat']]) ? $ucats[$a['_cat']]+$u : $u);
			$items[] = $a;
		}
	}

	if($caching && Eleanor::$caching) {
		Eleanor::$last_mod = $lmod;
		$etag = Eleanor::$etag;
		Eleanor::$etag = md5($uid . $ids . $Eleanor->module['config']['n'] . $Eleanor->module['config']['etag']);
		if(Eleanor::$modified && Eleanor::$last_mod && Eleanor::$last_mod <= Eleanor::$modified && $etag && $etag==Eleanor::$etag)
			return Start();
		else
			Eleanor::$modified=false;
	}

	foreach($ucats as $v) {
		$v = $Eleanor->Url->Construct($v,true,$Eleanor->Url->delimiter);
	}
	return compact('items','ucats');
}

function GetGN()
{global$Eleanor;
	$gn=Eleanor::GetCookie($Eleanor->module['config']['n'].'-gn');
	$gns=Eleanor::GetCookie($Eleanor->module['config']['n'].'-gns');

	if($gn and $gns and $gns===md5($gn.$Eleanor->module['config']['secret']))
		return explode(',',$gn);
	return array();
}